<?php
/**
 * Galdic project
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Galdic
 * @package    Galdic
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Admin_UserController
 * 
 * @package    Galdic
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: UserController.php 1 2009-09-14 16:53:52Z vifito $
 */
class Admin_UserController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;
    
    /**
     * Check session 
     */
    public function preDispatch()
    {
        $session = Zend_Registry::get('session');
        $actionName = $this->getRequest()->getActionName();
        
        if(!isset($session->username) && ($actionName!='login')) {
            $this->_redirect('/admin/user/login/');
        } elseif( isset($session->username) ) {
            $this->view->username = $session->username;
        }
    }

    public function init()
    {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
    }

    public function indexAction()
    {
        $this->view->title = "Usuarios";
        $this->view->headTitle($this->view->title, 'PREPEND');
        
        $users = new Admin_Model_DbTable_Users();
        $rows = $users->fetchAll(null, 'username ASC');
        
        // Pagination
        $paginator = Zend_Paginator::factory($rows);        
        $page = $this->_request->getParam('page');
        $paginator->setCurrentPageNumber($page);
        
        $this->view->assign('users', $paginator);
        $this->view->assign('messages', $this->_flashMessenger->getMessages());
    }

    public function addAction()
    {
        $this->view->title = "Novo usuario";
        $this->view->headTitle($this->view->title, 'PREPEND');
        
        $form = new Admin_Form_User();
        
        $form->passwd->setRequired(true)
                     ->setAttrib('dojoType', 'dijit.form.ValidationTextBox')
                     ->setAttrib('required', 'true')
                     ->setAttrib('intermediateChanges', 'false')
                     ->setAttrib('invalidMessage', 'Ten que inserir un contrasinal.');
                     
        $form->confirm_passwd->setRequired(true)
                     ->setAttrib('dojoType', 'dijit.form.ValidationTextBox')                     
                     ->setAttrib('required', 'true')
                     ->setAttrib('constraints', "{'other': 'passwd'}")
                     ->setAttrib('validator', 'confirmPassword')
                     ->setAttrib('intermediateChanges', 'false')
                     ->setAttrib('invalidMessage', 'Este contrasinal non coincide co anterior.');
        
        $this->view->form = $form;
        
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if($form->isValid($formData) && ($formData['passwd']==$formData['confirm_passwd'])) {
                $abbr = new Admin_Model_DbTable_Users();
                
                $data = $form->bindPostData($formData, $this->_flashMessenger);
                
                $abbr->insert($data);                
                
                $this->_redirect('/admin/user/'); // Listado de usuarios
            } else {
                $form->populate($formData);
            }            
        }
    }

    public function deleteAction()
    {
        $this->view->title = "Dar de baixa";
        $this->view->headTitle($this->view->title, 'PREPEND');
        
        if($this->getRequest()->isPost()) {
            $action = $this->getRequest()->getPost('action');                        
            if($action == 'Si') {
                $id = $this->getRequest()->getPost('id');
                
                $user = new Admin_Model_DbTable_Users();
                $user->delete('`id`='.(int)$id);                                
            }
                
            $this->_redirect('/admin/user/'); 
        } else {
            $id = $this->_getParam('id', 0);
            $user = new Admin_Model_DbTable_Users();
            $this->view->user = $user->fetchRow('`id`='.(int)$id);
        }
    }

    public function editAction()
    {
        $this->view->title = "Modificar datos";
        $this->view->headTitle($this->view->title, 'PREPEND');
        
        $form = new Admin_Form_User();
        
        $form->passwd->setRequired(false)
                     ->setAttrib('dojoType', 'dijit.form.ValidationTextBox')
                     ->setAttrib('intermediateChanges', 'false');
                     
        $form->confirm_passwd->setRequired(false)
                     ->setAttrib('dojoType', 'dijit.form.ValidationTextBox')                     
                     ->setAttrib('constraints', "{'other': 'passwd'}")
                     ->setAttrib('validator', 'confirmPassword')
                     ->setAttrib('intermediateChanges', 'false')
                     ->setAttrib('invalidMessage', 'Este contrasinal non coincide co anterior.');
        
        
        $this->view->form = $form;
        
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if($form->isValid($formData)) {
                $user = new Admin_Model_DbTable_Users();
                
                $data = $form->bindPostData($formData, $this->_flashMessenger);                
                unset($data['id']);
                
                $user->update($data, '`id`='.(int)$formData['id']);                
                
                $this->_redirect('/admin/user/'); 
            } else {
                $form->populate($formData);
            }            
        } else {
            $id = $this->_getParam('id', 0);
            if($id > 0) {
                $user = new Admin_Model_DbTable_Users();                
                $form->populate( $user->fetchRow('`id`='.(int)$id)->toArray() );
            } else {
                $this->_redirect('/admin/user/add/');
            }            
        }
    }

    public function loginAction()
    {
        $this->view->title = "Panel de Control";
        $this->view->headTitle($this->view->title, 'PREPEND');        
        
        if($this->getRequest()->isPost()) {
            // Get params
            $username = $this->getRequest()->getPost('username');
            $passwd   = $this->getRequest()->getPost('passwd');            
            
            $table = new Admin_Model_DbTable_Users();
            $row   = $table->fetchRow('`username`=' . $table->getAdapter()->quote($username) );   
            
            // Password encrypted with sha1 function hash
            if(isset($row->username) && ($row->passwd == sha1($passwd))) {
                
                // Create session and redirect
                $session = Zend_Registry::get('session');
                $session->username = $row->username;
                $session->email    = $row->email;
                
                // Redirect to /admin/panel/
                $this->_redirect('/admin/panel/'); 
            }
            
            $this->view->message = 'Credenciais incorrectas.';
        }
        
        $form = new Admin_Form_Login();        
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $session = Zend_Registry::get('session');
        unset($session->username);
        unset($session->email);
        
        $this->_redirect('/admin/user/login/');
    }


}













